package cn.com.callback

import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.com.elite.EliteBean;

public class auto5GSendMessage implements CallBackInvoke {
    private static final Logger log = LoggerFactory.getLogger(auto5GSendMessage.class);

    public void doCallBack(EliteBean eliteBean, String callBack, Map map, String paramString) {

        log.warn("---auto5GSendMessage---");
        //查找待发送任务
        List getSmsSelectSQL = eliteBean.chaxun_sql('''Select Documentout_Guid,
                                                               Doctype,
                                                               Documentto,
                                                               Documentpath,
                                                               Documentpath2,
                                                               Lockedby,
                                                               '' Openid,
                                                               Template_Id,
                                                               Stringfield1,
                                                               '' Msgid
                                                          From Documentout With(Nolock)
                                                         Where Doctype = 6
                                                           And Status = 3
                                                           And Sub_Doctype = '1'
                                                           And Trialcount < Trialcountlimit
                                                           And Isnull(Expectedstartdate, Getdate()) <= Getdate()
                                                         Order By Priority_Id, Isnull(Expectedstartdate, Getdate()), Createddate''', "dataSource");
        log.debug("SQL获取待发送数据量:" + getSmsSelectSQL.size());

        for (int i = 0; i < getSmsSelectSQL.size(); i++) {

            Map selectResultcm = getSmsSelectSQL.get(i);
            String Documentout_Guid = selectResultcm.get("Documentout_Guid");
            String Doctype = selectResultcm.get("Doctype");
            String Documentto = selectResultcm.get("Documentto");
            String Documentpath = selectResultcm.get("Documentpath");
            String Documentpath2 = selectResultcm.get("Documentpath2");
            String Template_Id = selectResultcm.get("Template_Id");
            String Open_Id = selectResultcm.get("OpenId");
            String URL = selectResultcm.get("Stringfield1");
            String opsource = selectResultcm.get("Lockedby");
            String Msgid = selectResultcm.get("Msgid");

            if (Doctype == "6") {
                doSendSMS(eliteBean, Documentout_Guid, Documentto, Documentpath2, Msgid, Template_Id);

            } else {
                log.warn("未知的消息类型-本条任务结束");
            }
        }

    }

    /**
     * 发送短信消息
     * @param s1
     * @param s2
     * @param s3
     */
    public static void doSendSMS(EliteBean eliteBean, String Documentout_Guid, String Documentto, String Documentpath2, String Msgid, String Template_Id) {

        // 开始准备发送
        JSONObject sendResultJson = sendSWSms(eliteBean, Documentout_Guid, Documentto, Documentpath2, Msgid, Template_Id);

        if (sendResultJson.getString("code") == "200") {
            // 发送成功
            String failCode = sendResultJson.getString("ResultID");
            String failDesc = sendResultJson.getString("Description");
            eliteBean.update("Update Documentout Set Status = '1', Failcode = '" + failCode + "', Faildescription = '" + failDesc + "', Trialcount = Trialcount + 1, Lasttrydatetime = Getdate(), Finishdatetime = Getdate() Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
        } else {
            // 发送失败
            String failCode = sendResultJson.getString("code");
            String failDesc = sendResultJson.getString("msg");
            eliteBean.update("Update Documentout Set Status = Case When Trialcount + 1 >= Trialcountlimit Then '-1' Else Status End, Failcode = '" + failCode + "', Faildescription = '" + failDesc + "', Trialcount = Trialcount + 1, Lasttrydatetime = Getdate() Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
        }

    }

    public static JSONObject sendSWSms(EliteBean eliteBean, String Documentout_Guid, String Documentto, String Documentpath2, String Msgid, String Template_Id) {
        JSONObject resultSendSms = new JSONObject();

        log.debug("sendAliSms参数-Documentout_Guid:" + Documentout_Guid + " Documentto:" + Documentto + " Documentpath2:" + Documentpath2 + " Msgid:" + Msgid + " Template_Id:" + Template_Id);

        try {
            // 获取发送所需要的Token
            String DOMAIN = KHDBConfig.getAPIURL(eliteBean, "EliteInner-API");
            JSONObject apiTokenJson = JSONObject.fromObject(Util.doHttpGet(DOMAIN + "/apiGetToken?appid=5GSMS", "UTF-8", 5000, 0));
            String access_token = apiTokenJson.getJSONObject("data").getString("access_token");

            // 处理头文件
            Map<String, String> headParams = new HashMap<String, String>();
            headParams.put("Content-Type", "application/json");
            headParams.put("Authorization", "Bearer " + access_token);
            headParams.put("serverRoot", KHDBConfig.getAPIURL(eliteBean, "5G-SMS-rootUrl"));

            JSONObject postJson = new JSONObject();
            postJson.put("templateId", Template_Id);

            JSONArray phonesList = new JSONArray();
            JSONObject phones = new JSONObject();
            JSONArray paramsList = JSONArray.fromObject(Documentpath2);

            phones.put("params", paramsList);
            phones.put("phoneNum", Documentto);

            phonesList.add(phones);
            postJson.put("phones", phonesList);

            System.out.println(postJson);

            String resultInfo = Util.doHttpPostUseHead(KHDBConfig.getAPIURL(eliteBean, "5G-SMS-sendUrl"), postJson.toString(), "UTF-8", 120000, 0, headParams);
            log.debug("调用PA短信发送返回：" + resultInfo);

            JSONObject resultJson = JSONObject.fromObject(resultInfo);
            String code = resultJson.getInt("code");

            resultSendSms.put("code", resultJson.getInt("code"));
            resultSendSms.put("msg", resultJson.getString("msg"));

            if (code == "200") {

                resultSendSms.put("ResultID", resultJson.getJSONObject("data").getString("taskId"));
                resultSendSms.put("Description", resultJson.getJSONObject("data").getInt("failCount"));

                log.debug("调用PA短信发送SuccessList结果：" + resultSendSms.toString());

            }

            log.debug("调用PA短信发送结果：" + resultSendSms.toString());

        } catch (Exception e1) {
            log.error("调用PA短信发送异常：", e1);
            resultSendSms.put("code", "-1");
            resultSendSms.put("msg", e1.getMessage());

        }

        return resultSendSms;
    }
}
